package com.ushine.web.communication.websocket.contrroller;


import com.ushine.web.communication.websocket.WebSocketService;
import com.ushine.web.communication.websocket.model.WebSocketMsg;
import com.ushine.web.component.http.HttpResponseVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @Author: yls
 * @Date: 2021/1/20 14:40
 * @Description: websocket 测试
 * @Version 1.0
 */
@RestController
@RequestMapping("sys")
@Api(tags = "websocket-即时通信")
@Slf4j
public class SysWsController {

    @Resource
    WebSocketService webSocketService;

    /**
     * //@MessageMapping和@RequestMapping功能类似，用于设置URL映射地址，浏览器向服务器发起请求，需要通过该地址。
     * 如果服务器接收到了消息，就会对订阅了@SendTo括号中的地址传送消息。
     */
    @MessageMapping("/send/{id}")
    @SendTo("/topic/user/{id}")
    public HttpResponseVO<WebSocketMsg> say(WebSocketMsg webSocketMsg) {
        log.info("测试MessageMapping");
        webSocketMsg.setName("你好，连接成功");
        log.info(webSocketMsg.toString());
        return new HttpResponseVO<WebSocketMsg>().ok("发送成功", webSocketMsg);
    }


    @ResponseBody
    @GetMapping("/pushToAll")
    public void subscribe() {
        HttpResponseVO<Object> httpResponseVO = new HttpResponseVO<>().ok("广播测试");
        webSocketService.sendMsg(httpResponseVO);
    }


    @GetMapping("/user/send/{id}")
    @SendTo("/topic/user/{id}")
    public void send(@PathVariable String id) {
        WebSocketMsg webSocketMsg = new WebSocketMsg();
        webSocketMsg.setContent(id);
        webSocketMsg.setName("你好，连接成功");
        log.info(webSocketMsg.toString());

        HttpResponseVO<WebSocketMsg> ok = new HttpResponseVO<WebSocketMsg>().ok(id, webSocketMsg);
        ArrayList<String> arrayList = new ArrayList();
        arrayList.add("d892bf12bf7d11e793b69c5c8e6f60fb");
        webSocketService.send2Users(arrayList, ok);

    }


}
